package com.heima.app.gateway.filter;

import com.cjq.jwt.JwtUtil;
import com.heima.app.gateway.constant.RedisConstant;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;


@Component
public class AuthorizeFilter implements Ordered , GlobalFilter {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private JwtUtil jwtUtil;
//    @Override
//    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
//        ServerHttpRequest request = exchange.getRequest();
//        ServerHttpResponse response = exchange.getResponse();
//
//        boolean contains = request.getURI().getPath().contains("/login");
//        if (contains){
//            return chain.filter(exchange);
//        }
//
//        HttpHeaders headers = request.getHeaders();
//        String token = headers.getFirst("token");
//        if (token==null||token.isEmpty()){
//            response.setStatusCode(HttpStatus.UNAUTHORIZED);
//            return response.setComplete();
//        }
//        try {
//            Claims claims = AppJwtUtil.getClaimsBody(token);
//            int expire = AppJwtUtil.verifyToken(claims);
//            if (expire == 1 || expire == 2){
//                response.setStatusCode(HttpStatus.UNAUTHORIZED);
//                return response.setComplete();
//            }
//            if (claims != null) {
//                request.mutate().header("id",claims.get("id").toString()).build();
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//            response.setStatusCode(HttpStatus.UNAUTHORIZED);
//            return response.setComplete();
//        }
//
//
//
//        return chain.filter(exchange);
//    }



    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        boolean contains = request.getURI().getPath().contains("/login");
        if (contains){
            return chain.filter(exchange);
        }


        String token = getTokenFromHeader(request);
        if (isInValidStr(token)){
            return unauthorized(response);
        }


        Claims claims;
        try {
            claims = jwtUtil.parseToken(token, SignatureAlgorithm.HS256);
        } catch (Exception e) {
            return unauthorized(response);
        }

        if (claims == null) {
            return unauthorized(response);
        }


        Long userId = claims.get("id", Long.class);
        if (userId==0L){
            return chain.filter(exchange);
        }


        String jwtId = claims.getId();
        String rUserId;
        try {
            rUserId = redisTemplate.opsForValue().get(RedisConstant.APP_JWT_TOKEN_KEY + jwtId);
        } catch (Exception e) {
            return unauthorized(response);
        }


        if (isInValidStr(rUserId)){
            return unauthorized(response);
        }


        ServerHttpRequest id = request.mutate().header("id", rUserId).build();
        exchange.mutate().request(id).build();
        return chain.filter(exchange);
    }


    private String getTokenFromHeader(ServerHttpRequest request) {
        return request.getHeaders().getFirst("token");
    }

    private boolean isInValidStr(String token) {
        return StringUtils.isEmpty(token);
    }

    private Mono<Void> unauthorized(ServerHttpResponse response) {
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        return response.setComplete();
    }
    @Override
    public int getOrder() {
        return 0;
    }
}
